<!--
  * 支付配置列表
  *
  * @Author:    zzb
  * @Date:      2025-01-23 04:08:26
-->
<template>
  <!---------- 查询表单form begin ----------->

  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item label="通道名称" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.channelName" placeholder="输入通道名称" />
      </a-form-item>
      <a-form-item label="计费编号" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.chargeId" placeholder="计费编号" />
      </a-form-item>
      <a-form-item label="计费名称" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.chargeName" placeholder="输入计费名称" />
      </a-form-item>
      <!-- <a-form-item label="业务类型" class="smart-query-form-item">
        <a-select
          v-model:value="queryForm.businessType"
          style="width: 180px"
          allowClear
          :options="CHANNEL_BUSINESS_TYPE"
          placeholder="请选择业务类型"
        />
      </a-form-item> -->
      <a-form-item label="通道类型" class="smart-query-form-item">
        <a-select v-model:value="queryForm.channelType" style="width: 180px" allowClear :options="ZZB_CHANNEL_TYPE" placeholder="请选择通道类型" />
      </a-form-item>
      <a-form-item label="状态" class="smart-query-form-item">
        <a-select v-model:value="queryForm.status" style="width: 180px" allowClear :options="ZZB_CHANNEL_STATUS" placeholder="请选择状态" />
      </a-form-item>
      <a-form-item label="产品名称" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.productName" placeholder="输入产品名称" />
      </a-form-item>
      <a-form-item class="smart-query-form-item">
        <a-button type="primary" @click="onSearch">
          <template #icon>
            <SearchOutlined />
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery" class="smart-margin-left10">
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>

  <!-- <a-alert
    class="notice-alert"
    message="注意：通道配置正式启用后将不可变更，未启用或试用期间可以变更参数信息！试用期间可进行分润，启用后方可正式启用！"
    type="warning"
    :show-icon="false"
    banner
    style="background-color: #f59a23; color: #ffffff; height: 58px; line-height: 58px; font-size: 16px"
  /> -->
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-title">数据列表</div>
      <div class="smart-table-operate-block">
        <!-- <a-button @click="showForm" type="primary" size="small" v-privilege="'payconfig:insert'">
          <template #icon>
            <PlusOutlined />
          </template>
          添加
        </a-button> -->
        <!-- <TableOperator v-model="columns" :tableId="null" :refresh="queryData" /> -->
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->

    <!---------- 表格 begin ----------->
    <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :loading="tableLoading" :pagination="false">
      <template #bodyCell="{ record, column }">
        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate">
            <a-button @click="showForm(record, 'view')" type="link" v-privilege="'agent_payconfig:update'">详情</a-button>
            <a-button @click="showForm(record, 'update')" type="link" v-if="record.status === 0" v-privilege="'agent_payconfig:update'"
              >配置</a-button
            >
            <a-button
              v-for="button in filteredButtons(record)"
              :key="button.text"
              @click="showModal(button.title, record, button.text, button.content1, button.content2)"
              type="link"
            >
              {{ button.text }}
            </a-button>
          </div>
        </template>
      </template>
    </a-table>
    <!---------- 表格 end ----------->

    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize"
        v-model:current="queryForm.pageNo"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="queryData"
        @showSizeChange="queryData"
        :show-total="(total) => `共${total}条`"
      />
    </div>

    <ChannelsForm ref="formRef" @reloadList="queryData" />
    <!-- <ChannelConfigForm ref="configFormRef" @reloadList="queryData" /> -->
  </a-card>
  <div v-if="isModalVisible" class="custom-modal">
    <div class="modal-content">
      <h3 id="modal-title">{{ modalTitle }}</h3>
      <div class="modal-message">
        <ExclamationCircleOutlined id="modal-icon" class="icon-warning" />
        <div>
          <p id="modal-content">{{ modalContent1 }}</p>
          <p id="modal-content2">{{ modalContent2 }}</p>
        </div>
      </div>
      <div class="modal-buttons">
        <button id="modal-ok" @click="handleOkClick">确定</button>
        <button id="modal-cancel" @click="hideModal">取消</button>
      </div>
    </div>
  </div>
</template>
<script setup>
  import { reactive, ref, onMounted, computed, getCurrentInstance } from 'vue'
  import { message } from 'ant-design-vue'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { payconfigPage, payconfigFindId, payconfigUpdateStatus } from '/@/api/business/b-agent/channel/pay-config-api'
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const'
  import { smartSentry } from '/@/lib/smart-sentry'
  import TableOperator from '/@/components/support/table-operator/index.vue'
  import ChannelsForm from '/@/views/business/b-agent/agent-channel/channel-form.vue'
  import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue'
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
  //import FilePreview from '/@/components/support/file-preview/role-user-list.vue'; // 图片预览组件
  // import { useUserStore } from '/@/store/modules/system/user'
  import { privilege, strToArr } from '/@/utils/common'
  import { selectDictLabel } from '/@/utils/common'
  import {
    ZZB_CHANNEL_TYPE, //通道类型
    CHANNEL_BUSINESS_TYPE, // 通道业务类型
    CHARGE_TYPE, // 计费模式
    ZZB_CHANNEL_STATUS,
  } from '/@/constants/dict'

  // console.log('useUserStore===>', useUserStore().userInfo)
  const { proxy } = getCurrentInstance()

  const statusTypeColorArray = ['red', 'blue']
  // ---------------------------- 表格列 ----------------------------

  const columns = ref([
    {
      title: '序号',
      dataIndex: 'index',
      width: 60,
      customRender: ({ index }) => {
        return (queryForm.pageNo - 1) * queryForm.pageSize + index + 1
      },
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      ellipsis: true,
    },
    {
      title: '通道名称（品牌）',
      dataIndex: 'channelName',
      ellipsis: true,
    },
    {
      title: '公司名称',
      dataIndex: 'companyName',
      ellipsis: true,
    },
    {
      title: '计费编号',
      dataIndex: 'chargeId',
      ellipsis: true,
    },
    {
      title: '通道类型',
      dataIndex: 'channelType',
      customRender: ({ text }) => {
        return selectDictLabel(ZZB_CHANNEL_TYPE, text)
      },
      ellipsis: true,
    },
    {
      title: '计费名称',
      dataIndex: 'chargeName',
      ellipsis: true,
    },
    {
      title: '计费模式',
      dataIndex: 'chargeType',
      customRender: ({ text }) => {
        return selectDictLabel(CHARGE_TYPE, text)
      },
      ellipsis: true,
    },
    {
      title: '业务类型',
      dataIndex: 'businessType',
      ellipsis: true,
      customRender: ({ text }) => {
        return strToArr(text)
          .map((item) => selectDictLabel(CHANNEL_BUSINESS_TYPE, item))
          .join(',')
        // return selectDictLabel(CHANNEL_BUSINESS_TYPE, text)
        // return getBusinessName(record.businessType) || '未知'
      },
    },
    // {
    //   title: '线上成本',
    //   dataIndex: 'costOnlineRate',
    //   ellipsis: true,
    //   customRender: ({ record }) => {
    //     return record.defaultedFlag === true ? record.dCostOnlineRate : record.costOnlineRate
    //   },
    // },
    // {
    //   title: '线下成本',
    //   dataIndex: 'costOfflineRate',
    //   ellipsis: true,
    //   customRender: ({ record }) => {
    //     return record.defaultedFlag === true ? record.dCostOfflineRate : record.costOfflineRate
    //   },
    // },
    // {
    //   title: '参数',
    //   dataIndex: 'defaultedFlag',
    //   ellipsis: true,
    //   customRender: ({ text }) => {
    //     return text === true ? '默认' : '自定义'
    //   },
    // },
    {
      title: '排序',
      dataIndex: 'num',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      customRender: ({ text }) => {
        return selectDictLabel(ZZB_CHANNEL_STATUS, text)
      },
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      minWidth: 180,
    },
  ])

  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    channelName: undefined,
    chargeName: undefined,
    chargeId: undefined,
    productName: undefined,
    businessType: undefined,
    channelType: undefined,
    status: undefined,
    pageNo: 1,
    pageSize: 10,
  }
  // 查询表单form
  const queryForm = reactive({ ...queryFormState })
  // 表格加载loading
  const tableLoading = ref(false)
  // 表格数据
  const tableData = ref([])
  // 总数
  const total = ref(0)

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize
    Object.assign(queryForm, queryFormState)
    queryForm.pageSize = pageSize
    queryData()
  }

  // 搜索
  function onSearch() {
    queryForm.pageNo = 1
    queryData()
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true
    try {
      let queryResult = await payconfigPage(queryForm)
      tableData.value = queryResult.data
      total.value = queryResult.total
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      tableLoading.value = false
    }
  }

  // const getBusinessName = (value) => {
  //   const item = CHANNEL_BUSINESS_TYPE.find((item) => item.value === value)
  //   return item ? item.itemName : null
  // }

  onMounted(() => {
    queryData()
    // getBusinessList()
  })

  // ---------------------------- 添加/修改 ----------------------------
  const formRef = ref()

  function showForm(data, type) {
    formRef.value.show(data, type)
  }

  // ---------------------------- 批量删除 ----------------------------

  // 选择表格行
  const selectedRowKeyList = ref([])

  function onSelectChange(selectedRowKeys) {
    selectedRowKeyList.value = selectedRowKeys
  }

  // 模态框状态
  const isModalVisible = ref(false)
  const modalTitle = ref('')
  const modalContent1 = ref('')
  const modalContent2 = ref('')
  const id = ref('')
  const isDev = import.meta.env.MODE !== 'production'

  // 按钮数据
  const buttons = [
    // {
    //   text: '试用',
    //   title: '确认提示',
    //   content1: '是否试用该通道',
    //   show: (record) => record.status === 0 && isDev,
    //   privilege: 'agent_payconfig:update_status',
    // },
    {
      text: '正式启用',
      title: '确认提示',
      content1: '是否正式启用该通道',
      content2: '正式启用后，相关配置不可修改',
      show: (record) => record.status === 0 || record.status === 1,
      privilege: 'agent_payconfig:update_status',
    },
    {
      text: '关闭',
      title: '通道关闭提示',
      content1: '是否确认关闭该通道',
      content2: '通道关闭后，将于次月1日生效。确认关闭后，将推送信息至开通该通道的商户。商户可直接通过官方渠道继续使用该机构提供的服务。',
      show: (record) => record.status === 2 || record.status === 1 || record.status === 0,
      privilege: 'agent_payconfig:update_status',
    },
  ]

  // 创建计算属性
  const filteredButtons = computed(() => {
    return (record) => {
      return buttons.filter((button) => {
        return button.show(record) && privilege(button.privilege)
      })
    }
  })

  const button_text = ref('')
  // 显示模态框
  const showModal = (title, record, text, content1, content2) => {
    modalTitle.value = title
    modalContent1.value = content1
    modalContent2.value = content2
    button_text.value = text
    isModalVisible.value = true
    id.value = record.id
  }

  // 隐藏模态框
  const hideModal = () => {
    isModalVisible.value = false
  }
  // 确定按钮的逻辑
  const handleOkClick = () => {
    const params = {
      id: id.value,
      status: 0,
    }
    //TODO <chengsh> 枚举
    if (button_text.value == '试用') {
      params.status = 1
    }
    if (button_text.value == '正式启用') {
      params.status = 2
    }
    if (button_text.value == '关闭') {
      params.status = 3
    }
    payconfigUpdateStatus(params).then(() => {
      queryData()
    })
    // 模拟成功
    hideModal()
  }

  // 配置通道
  const configFormRef = ref()
  async function onConfig(record) {
    try {
      SmartLoading.show()
      // 如果 data 是 undefined，表示新增，不需要查询
      if (record) {
        const param = {
          id: record.id,
        }
        const queryResult = await payconfigFindId(param)
        record = queryResult.data // 使用后端返回的最新数据
      }
      configFormRef.value.show(record)
    } catch (e) {
      smartSentry.captureError(e)
      message.error('获取数据失败')
    } finally {
      SmartLoading.hide()
    }
  }
</script>

<style lang="less" scoped>
  .notice-alert {
    margin-bottom: 16px;

    :deep(.ant-alert) {
      &.ant-alert-warning {
        background-color: #f59a23;
        border: none;
        padding: 16px 24px;

        .ant-alert-message {
          color: #ffffff;
        }
      }
    }
  }

  .smart-table-btn-block {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    justify-content: space-between;
  }

  .smart-table-title {
    font-size: 16px;
    font-weight: 500;
  }

  .smart-table-operate-block {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .custom-modal {
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1000;
  }

  .modal-content {
    width: 400px;
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    text-align: center;
  }

  #modal-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 10px;
  }

  .modal-message {
    display: flex;
    align-items: center; /* 垂直居中 */
    margin-bottom: 20px;
  }

  #modal-icon {
    color: #f0ad4e; /* 警告图标的颜色 */
    font-size: 24px;
    margin-right: 10px;
  }

  #modal-content {
    font-size: 14px;
    color: #333;
  }

  .modal-buttons {
    display: flex;
    justify-content: center;
    gap: 10px;
  }

  #modal-ok {
    background-color: #007bff;
    color: #fff;
    border: none;
    padding: 8px 20px;
    border-radius: 4px;
    cursor: pointer;
  }

  #modal-cancel {
    background-color: #f0f0f0;
    color: #333;
    border: 1px solid #ccc;
    padding: 8px 20px;
    border-radius: 4px;
    cursor: pointer;
  }
</style>
